const path = require('path');
const fs = require('fs');
const glob = require('glob');

module.exports = {
  searchPackageJSONDir (dir) {
    let result;
    let _dir = dir || __dirname;
    let files = fs.readdirSync(_dir, 'utf-8')
    files.forEach(file => {
      if (file === 'package.json') {
        result = _dir;
      }
    });
    if (result) {
      return result;
    } else {
      _dir = path.resolve(_dir, '..');
      result = this.searchPackageJSONDir(_dir);
    }
    return result;
  },

  getAllFiles (dir) {
    let result = [];
    return new Promise((resolve, reject) => {
      glob(dir, (err, files) => {
        if (err) {
          return reject(err);
        }
        files.forEach(file => {
          if (this.isFile(file)) {
            result.push(file);
          }
        });
        resolve(result);
      });
    });
  },

  isFile (_path) {
    let result = false;
    try {
      let stats = fs.statSync(_path);
      result = stats.isFile();
    } catch (err) {}
    return result;
  },

  isDirectory (_path) {
    let result = false;
    try {
      let stats = fs.statSync(_path);
      result = stats.isDirectory();
    } catch (err) {}
    return result;
  }
}
